package com.gaogzhen.datastructure.graph.undirected;

import com.gaogzhen.datastructure.stack.Stack;
import edu.princeton.cs.algs4.Graph;

import java.util.Iterator;

/**
 * 二分图
 * @author: Administrator
 * @createTime: 2023/03/10 19:27
 */
public class Bipartite {
    /**
     * 标记顶点
     */
    private boolean[] marked;

    /**
     * 记录所有顶点到起点的路径
     */
    private int[] edgeTo;

    /**
     * 双色标记顶点颜色,true和false
     */
    private boolean[] color;

    /**
     * 是否是二分图标志，默认true
     */
    private boolean isBipartite = true;

    /**
     * 如果不是二分图，记录形成同色边所在环
     */
    private Stack<Integer> cycle;

    /**
     * 染色法检测是否是二分图
     *
     * @param G the undirected graph
     */
    public Bipartite(Graph G) {
        // 只是检测二分图可以不进行平行边的判断；如果想找到形成同色边所在环则需要进行平行边的判断
        // if (hasParallelEdges(G)) {
        //     return;
        // }

        // don't need special case to identify self-loop as a cycle
        // if (hasSelfLoop(G)) return;
        int len = G.V();
        marked = new boolean[len];
        color = new boolean[len];
        edgeTo = new int[len];
        for (int i = 0; i < len; i++) {
            edgeTo[i] = -1;
        }
        dfs(G);
    }

    private void dfs(Graph G) {
        Stack<Node> stack = new Stack<>();
        for (int v = 0; v < G.V(); v++) {
            if (!marked[v]) {
                if (dfs(G, v, stack) ) {
                    return;
                }
            }
        }
    }

    /**
     * 深度优先染色
     *
     * @param G     无向图
     * @param v
     * @param stack
     */
    private boolean dfs(Graph G, int v, Stack<Node> stack) {
        marked[v] = true;
        Iterable<Integer> adj = G.adj(v);
        if (adj != null) {
            stack.push(new Node(v,adj.iterator()));
        }

        while (!stack.isEmpty()) {
            Node c = stack.pop();

            while (c.adj.hasNext()) {
                Integer w = c.adj.next();
                if (!marked[w]) {
                    marked[w] = true;
                    edgeTo[w] = c.v;
                    // 当前顶点染和其父结点相反的颜色
                    color[w] = !color[c.v];
                    if (c.adj.hasNext()) {
                        stack.push(c);
                    }
                    Iterable<Integer> adjW = G.adj(w);
                    if (adjW != null) {
                        stack.push(new Node(w, adjW.iterator()));
                    }
                    break;
                }

                // check for cycle (but disregard reverse of edge leading to v)
                else if (color[w] == color[c.v]) {
                    // 记录同色边所在环路
                    cycle = new Stack<>();
                    cycle.push(w);
                    for (int x = c.v; x != w; x = edgeTo[x]) {
                        cycle.push(x);
                    }
                    cycle.push(w);
                    isBipartite = false;
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检测无向图G是否有子环
     * @param G
     * @return
     */
    private boolean hasSelfLoop(Graph G) {
        for (int v = 0; v < G.V(); v++) {
            for (int w : G.adj(v)) {
                if (v == w) {
                    cycle = new Stack<Integer>();
                    cycle.push(v);
                    cycle.push(v);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检测无向图G是否有平行边
     * @param G
     * @return
     */
    private boolean hasParallelEdges(Graph G) {
        marked = new boolean[G.V()];

        for (int v = 0; v < G.V(); v++) {

            // check for parallel edges incident to v
            for (int w : G.adj(v)) {
                if (marked[w]) {
                    cycle = new Stack<Integer>();
                    cycle.push(v);
                    cycle.push(w);
                    cycle.push(v);
                    return true;
                }
                marked[w] = true;
            }

            // reset so marked[v] = false for all v
            for (int w : G.adj(v)) {
                marked[w] = false;
            }
        }
        return false;
    }

    /**
     * 是否是二分图
     * @return
     */
    public boolean isBipartite() {
        return isBipartite;
    }

    public boolean color(int v) {
        validateVertex(v);
        if (!isBipartite) {
            throw new UnsupportedOperationException("graph is not bipartite");
        }
        return color[v];
    }

    private void validateVertex(int v) {
        int V = marked.length;
        if (v < 0 || v >= V) {
            throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
        }
    }

    /**
     * 如果有环，返回环路
     * @return a cycle if the graph {@code G} has a cycle,
     *         and {@code null} otherwise
     */
    public Iterable<Integer> cycle() {
        return cycle;
    }



    static class Node {

        /**
         * 顶点索引
         */
        private int v;


        /**
         * 顶点邻接表
         */
        private Iterator<Integer> adj;

        public Node(int v, Iterator<Integer> adj) {
            this.v = v;
            this.adj = adj;
        }
    }
}
